<template>
  <el-dialog
    v-model="visible"
    title="打印预览"
    width="80%"
    :destroy-on-close="true"
    @close="handleClose"
  >
    <div class="print-preview-container">
      <!-- 打印预览区域 -->
      <div v-if="previewLoading" class="loading-container">
        <div class="loading-content">
          <div class="loading-spinner"></div>
          <div class="loading-text">加载预览中...</div>
        </div>
      </div>
      
      <div v-else-if="orderData" class="preview-content">
        <!-- 打印内容区域 -->
        <div id="printable-area" class="printable-area">
          <!-- 订单头部信息 -->
          <div class="order-header">
            <h1 class="order-title">订单打印</h1>
            <div class="order-info">
              <div class="info-item">
                <span class="label">订单号：</span>
                <span class="value">{{ orderData.order_no }}</span>
              </div>
              <div class="info-item">
                <span class="label">创建时间：</span>
                <span class="value">{{ formatDate(orderData.order_time) }}</span>
              </div>
            </div>
          </div>
          
          <!-- 客户信息 -->
          <div class="customer-info">
            <h3 class="section-title">客户信息</h3>
            <div class="info-grid">
              <div class="info-item">
                <span class="label">姓名：</span>
                <span class="value">{{ orderData.customer_name || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="label">电话：</span>
                <span class="value">{{ orderData.customer_phone || '-' }}</span>
              </div>
            </div>
          </div>
          
          <!-- 商品明细 -->
          <div class="items-section">
            <h3 class="section-title">商品明细</h3>
            <div class="items-table">
              <div class="table-header">
                <div class="header-cell">商品名称</div>
                <div class="header-cell">数量</div>
                <div class="header-cell">单价</div>
                <div class="header-cell">小计</div>
              </div>
              <div class="table-body">
                <div 
                  v-for="(item, index) in (orderData.items || [])" 
                  :key="index" 
                  class="table-row"
                >
                  <div class="table-cell">{{ item.name || '-' }}</div>
                  <div class="table-cell">{{ item.quantity || 0 }}</div>
                  <div class="table-cell">¥{{ item.price || 0 }}</div>
                  <div class="table-cell">¥{{ calculateSubtotal(item) }}</div>
                </div>
              </div>
              <div class="table-footer">
                <div class="total-cell">
                  <span class="total-label">总计：</span>
                  <span class="total-value">¥{{ calculateTotal() }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <div v-else class="error-container">
        <el-empty description="订单数据加载失败" />
      </div>
    </div>
    
    <!-- 对话框底部按钮 -->
    <template #footer>
      <el-button @click="handleClose">关闭</el-button>
      <el-button 
        v-if="!previewOnly"
        type="primary" 
        @click="handlePrint" 
        :loading="printing"
        :disabled="!orderData || previewLoading"
      >
        打印
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { orderApi } from '../services/api';

// Props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  orderId: {
    type: [Number, null],
    default: null
  },
  previewOnly: {
    type: Boolean,
    default: false
  }
});

// Emits
const emit = defineEmits(['update:modelValue', 'print-success']);

// 响应式数据
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
});
const orderData = ref(null);
const previewLoading = ref(false);
const printing = ref(false);

// 监听显示状态，加载订单详情
watch(() => props.modelValue, async (newVal) => {
  if (newVal && props.orderId) {
    await loadOrderDetail();
  }
});

// 监听订单ID变化，重新加载
watch(() => props.orderId, async (newId) => {
  if (visible.value && newId) {
    await loadOrderDetail();
  }
});

// 加载订单详情
const loadOrderDetail = async () => {
  if (!props.orderId) return;
  
  previewLoading.value = true;
  try {
      const response = await orderApi.getOrderDetail(props.orderId);
    if (response) {
      // 确保items是数组
      if (typeof response.items === 'string') {
        try {
          response.items = JSON.parse(response.items);
        } catch (e) {
          response.items = [];
        }
      }
      orderData.value = response;
    } else {
      ElMessage.error('加载订单详情失败');
    }
  } catch (error) {
    console.error('加载订单详情失败:', error);
    ElMessage.error('加载订单详情失败');
  } finally {
    previewLoading.value = false;
  }
};

// 计算小计
const calculateSubtotal = (item) => {
  if (!item || !item.price || !item.quantity) return '0.00';
  return (item.price * item.quantity).toFixed(2);
};

// 计算总计
const calculateTotal = () => {
  if (!orderData.value?.items || !Array.isArray(orderData.value.items)) {
    return '0.00';
  }
  
  const total = orderData.value.items.reduce((sum, item) => {
    if (item.price && item.quantity) {
      return sum + (item.price * item.quantity);
    }
    return sum;
  }, 0);
  
  return total.toFixed(2);
};

// 格式化日期
const formatDate = (dateString) => {
  try {
    if (!dateString) return '-';
    const date = new Date(dateString);
    if (isNaN(date.getTime())) return dateString;
    
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  } catch (e) {
    return dateString || '-';
  }
};

// 处理浏览器打印
const handlePrint = async () => {
  printing.value = true;
  try {
    // 先调用浏览器打印
    window.print();
    
    // 获取打印机信息（这里使用默认值，实际项目中可能需要更复杂的实现）
    const printerInfo = {
      name: navigator.userAgent,
      timestamp: new Date().toISOString()
    };
    
    // 调用API更新订单状态并写入打印记录
    const response = await orderApi.printOrder(props.orderId, printerInfo);
    if (response && response.success) {
      ElMessage.success('打印成功');
      emit('print-success', props.orderId);
      // 关闭模态框
      visible.value = false;
    } else {
      ElMessage.error('更新打印状态失败');
    }
  } catch (error) {
    console.error('打印失败:', error);
    ElMessage.error('打印失败');
  } finally {
    printing.value = false;
  }
};

// 处理关闭
const handleClose = () => {
  visible.value = false;
  // 重置数据
  setTimeout(() => {
    orderData.value = null;
  }, 300);
};
</script>

<style scoped>
.print-preview-container {
  max-height: 70vh;
  overflow-y: auto;
}

.loading-container,
.error-container {
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 自定义加载样式 */
.loading-content {
  text-align: center;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(64, 158, 255, 0.2);
  border-radius: 50%;
  border-top-color: #409EFF;
  animation: spin 1s ease-in-out infinite;
  margin: 0 auto 16px;
}

.loading-text {
  color: #606266;
  font-size: 14px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.preview-content {
  padding: 20px 0;
}

/* 打印样式 */
.printable-area {
  background: white;
  padding: 40px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  max-width: 800px;
  margin: 0 auto;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 订单头部 */
.order-header {
  text-align: center;
  margin-bottom: 30px;
}

.order-title {
  font-size: 28px;
  margin: 0 0 20px 0;
  color: #303133;
  font-weight: bold;
}

.order-info {
  display: flex;
  justify-content: center;
  gap: 40px;
  font-size: 16px;
  color: #606266;
}

/* 信息区块 */
.customer-info,
.items-section {
  margin-bottom: 30px;
}

.section-title {
  font-size: 18px;
  margin: 0 0 15px 0;
  color: #303133;
  border-bottom: 2px solid #409EFF;
  padding-bottom: 8px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
}

.info-item {
  display: flex;
  align-items: center;
}

.info-item .label {
  font-weight: 500;
  color: #606266;
  margin-right: 8px;
  min-width: 60px;
}

.info-item .value {
  color: #303133;
}

/* 商品表格 */
.items-table {
  width: 100%;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
}

.table-header {
  display: grid;
  grid-template-columns: 3fr 1fr 1fr 1fr;
  background: #f5f7fa;
  padding: 12px 16px;
  border-bottom: 1px solid #e0e0e0;
}

.header-cell {
  font-weight: 600;
  color: #303133;
  text-align: center;
}

.table-body {
  border-bottom: 1px solid #e0e0e0;
}

.table-row {
  display: grid;
  grid-template-columns: 3fr 1fr 1fr 1fr;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
}

.table-row:last-child {
  border-bottom: none;
}

.table-cell {
  text-align: center;
  color: #606266;
}

.table-cell:first-child {
  text-align: left;
}

.table-footer {
  padding: 16px;
  background: #fafafa;
  text-align: right;
}

.total-cell {
  display: inline-flex;
  align-items: center;
  font-size: 16px;
}

.total-label {
  font-weight: 500;
  color: #606266;
  margin-right: 8px;
}

.total-value {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
}

/* 打印媒体样式 */
@media print {
  /* 隐藏所有非打印内容 */
  body > * {
    display: none !important;
  }
  
  /* 只显示打印区域 */
  .printable-area {
    display: block !important;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: 0;
    padding: 20px;
    border: none;
    box-shadow: none;
    max-width: 100%;
    background: white;
  }
  
  /* 确保对话框包装器不显示 */
  .el-dialog__wrapper {
    display: none !important;
  }
  
  /* 确保打印内容完全可见 */
  .print-preview-container,
  .preview-content {
    display: block !important;
    max-height: none;
    overflow: visible;
  }
  
  /* 重置所有容器的样式 */
  #app,
  .order-list,
  .el-main,
  .el-container {
    display: block !important;
    padding: 0;
    margin: 0;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .printable-area {
    padding: 20px;
  }
  
  .order-title {
    font-size: 24px;
  }
  
  .order-info {
    flex-direction: column;
    gap: 10px;
    align-items: center;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .table-header,
  .table-row {
    grid-template-columns: 2fr 1fr 1fr 1fr;
    font-size: 14px;
  }
}
</style>